{% extends "base.html" %}

{% block title %}数据统计 - 学生管理系统{% endblock %}

{% block scripts %}
{{ super() }}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
.bg-purple {
    background-color: #6f42c1 !important;
}
.bg-teal {
    background-color: #20c997 !important;
}
</style>
<script>
// 图表实例
let genderChart = null;
let gradeChart = null;
let ageChart = null;

// 获取统计数据
async function loadStatistics() {
    try {
        const response = await fetch('/api/stats');
        if (!response.ok) {
            throw new Error('获取统计数据失败');
        }
        const data = await response.json();
        
        // 更新概览卡片
        updateOverviewCards(data);
        
        // 更新图表
        updateCharts(data);
        
        // 更新时间
        document.getElementById('updateTime').textContent = new Date().toLocaleString();
        
    } catch (error) {
        console.error('加载统计信息失败:', error);
        alert('加载统计信息失败: ' + error.message);
    }
}

// 更新概览卡片
function updateOverviewCards(data) {
    document.getElementById('totalStudents').textContent = data.total || 0;
    
    // 统一计算男女数量
    let maleCount = 0;
    let femaleCount = 0;
    
    if (data.gender) {
        data.gender.forEach(item => {
            if (item._id === '男' || item._id === 'male') {
                maleCount += item.count;
            } else if (item._id === '女' || item._id === 'female') {
                femaleCount += item.count;
            }
        });
    }
    
    document.getElementById('maleCount').textContent = maleCount;
    document.getElementById('femaleCount').textContent = femaleCount;
    document.getElementById('gradeCount').textContent = data.grade ? data.grade.filter(item => item._id).length : 0;
    
    // 更新选课统计信息
    updateCourseStatsCards(data.course_stats, data.student_course_stats);
}

// 更新选课统计卡片
function updateCourseStatsCards(courseStats, studentCourseStats) {
    // 课程总数
    document.getElementById('totalCourses').textContent = courseStats.total_courses || 0;
    
    // 总选课人次
    document.getElementById('totalEnrollments').textContent = courseStats.total_enrollment || 0;
    
    // 平均选课数
    document.getElementById('avgCoursesPerStudent').textContent = studentCourseStats.avg_courses_per_student || 0;
    
    // 选课参与率
    document.getElementById('participationRate').textContent = studentCourseStats.participation_rate ? 
        studentCourseStats.participation_rate + '%' : '0%';
}

// 更新图表
function updateCharts(data) {
    // 性别分布饼图
    updateGenderChart(data.gender);
    
    // 年级分布柱状图
    updateGradeChart(data.grade);
    
    // 年龄分布折线图
    updateAgeChart(data.age);
    
    // 选课统计图表
    updateCourseCharts(data.course_stats, data.student_course_stats);
}

// 更新选课统计图表
function updateCourseCharts(courseStats, studentCourseStats) {
    // 热门课程图表
    updatePopularCoursesChart(courseStats.popular_courses);
    
    // 选课分布图表
    updateCourseDistributionChart(studentCourseStats.distribution);
}

// 更新热门课程图表
function updatePopularCoursesChart(popularCourses) {
    const ctx = document.getElementById('popularCoursesChart').getContext('2d');
    
    if (!popularCourses || popularCourses.length === 0) {
        document.getElementById('popularCoursesCard').style.display = 'none';
        return;
    }
    
    document.getElementById('popularCoursesCard').style.display = 'block';
    
    const chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: popularCourses.map(course => course.course_name),
            datasets: [{
                label: '选课人数',
                data: popularCourses.map(course => course.enrolled),
                backgroundColor: '#6610f2',
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            indexAxis: 'y',
            scales: {
                x: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
}

// 更新选课分布图表
function updateCourseDistributionChart(distribution) {
    const ctx = document.getElementById('courseDistributionChart').getContext('2d');
    
    if (!distribution || distribution.length === 0) {
        document.getElementById('courseDistributionCard').style.display = 'none';
        return;
    }
    
    document.getElementById('courseDistributionCard').style.display = 'block';
    
    const chart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: distribution.map(item => `${item.courses}门课程`),
            datasets: [{
                data: distribution.map(item => item.students),
                backgroundColor: [
                    '#6610f2', '#6f42c1', '#e83e8c', '#fd7e14', '#20c997',
                    '#0dcaf0', '#198754', '#ffc107', '#dc3545', '#6c757d'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.raw || 0;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((value / total) * 100).toFixed(1);
                            return `${label}: ${value}人 (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}

// 更新性别分布图表
function updateGenderChart(genderData) {
    const ctx = document.getElementById('genderChart').getContext('2d');
    
    // 过滤掉空值并统一性别格式
    const filteredData = genderData.filter(item => item._id);
    
    // 统一性别格式
    const unifiedData = [];
    const genderMap = {
        '男': 0,
        'male': 0,
        '女': 0,
        'female': 0,
        '未知': 0
    };
    
    filteredData.forEach(item => {
        if (item._id === '男' || item._id === 'male') {
            genderMap['男'] += item.count;
        } else if (item._id === '女' || item._id === 'female') {
            genderMap['女'] += item.count;
        } else {
            genderMap['未知'] += item.count;
        }
    });
    
    // 转换为数组格式
    const finalData = [
        { _id: '男', count: genderMap['男'] },
        { _id: '女', count: genderMap['女'] },
        { _id: '未知', count: genderMap['未知'] }
    ].filter(item => item.count > 0);
    
    if (genderChart) {
        genderChart.destroy();
    }
    
    genderChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: finalData.map(item => item._id),
            datasets: [{
                data: finalData.map(item => item.count),
                backgroundColor: [
                    '#0d6efd', // 深蓝色 - 男
                    '#6f42c1', // 紫色 - 女
                    '#fd7e14'  // 橙色 - 其他
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.raw || 0;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((value / total) * 100).toFixed(1);
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}

// 更新年级分布图表
function updateGradeChart(gradeData) {
    const ctx = document.getElementById('gradeChart').getContext('2d');
    
    // 过滤掉空值并按年级排序
    const filteredData = gradeData.filter(item => item._id).sort((a, b) => {
        const order = {'大一': 1, '大二': 2, '大三': 3, '大四': 4, '研究生': 5, '博士生': 6};
        return (order[a._id] || 99) - (order[b._id] || 99);
    });
    
    if (gradeChart) {
        gradeChart.destroy();
    }
    
    gradeChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: filteredData.map(item => item._id),
            datasets: [{
                label: '学生数量',
                data: filteredData.map(item => item.count),
                backgroundColor: '#0d6efd',
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
}

// 更新年龄分布图表
function updateAgeChart(ageData) {
    const ctx = document.getElementById('ageChart').getContext('2d');
    
    // 过滤掉空值并按年龄排序
    const filteredData = ageData.filter(item => item._id !== null).sort((a, b) => a._id - b._id);
    
    if (ageChart) {
        ageChart.destroy();
    }
    
    ageChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: filteredData.map(item => item._id + '岁'),
            datasets: [{
                label: '学生数量',
                data: filteredData.map(item => item.count),
                borderColor: '#36b9cc',
                backgroundColor: 'rgba(54, 185, 204, 0.1)',
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#36b9cc',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 4
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
}

// 刷新统计数据
function refreshStatistics() {
    loadStatistics();
}

// 页面加载时获取数据
document.addEventListener('DOMContentLoaded', function() {
    loadStatistics();
});
</script>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-chart-bar me-2"></i>数据统计</h2>
    <button class="btn btn-outline-primary" onclick="refreshStatistics()">
        <i class="fas fa-sync-alt me-1"></i>刷新数据
    </button>
</div>

<!-- 数据概览卡片 -->
<div class="row mb-4">
    <div class="col-md-2 mb-3">
        <div class="card bg-primary text-white">
            <div class="card-body text-center">
                <h5 class="card-title"><i class="fas fa-users"></i> 总学生数</h5>
                <h3 id="totalStudents" class="card-text">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card bg-success text-white">
            <div class="card-body text-center">
                <h5 class="card-title"><i class="fas fa-male"></i> 男生</h5>
                <h3 id="maleCount" class="card-text">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card bg-danger text-white">
            <div class="card-body text-center">
                <h5 class="card-title"><i class="fas fa-female"></i> 女生</h5>
                <h3 id="femaleCount" class="card-text">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card bg-info text-white">
            <div class="card-body text-center">
                <h5 class="card-title"><i class="fas fa-graduation-cap"></i> 年级数</h5>
                <h3 id="gradeCount" class="card-text">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card bg-warning text-white">
            <div class="card-body text-center">
                <h5 class="card-title"><i class="fas fa-book"></i> 课程总数</h5>
                <h3 id="totalCourses" class="card-text">0</h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card bg-secondary text-white">
            <div class="card-body text-center">
                <h5 class="card-title"><i class="fas fa-tasks"></i> 选课人次</h5>
                <h3 id="totalEnrollments" class="card-text">0</h3>
            </div>
        </div>
    </div>
</div>

<!-- 选课统计卡片 -->
<div class="row mb-4">
    <div class="col-md-6 mb-3">
        <div class="card bg-purple text-white">
            <div class="card-body text-center">
                <h5 class="card-title"><i class="fas fa-user-graduate"></i> 平均选课数</h5>
                <h3 id="avgCoursesPerStudent" class="card-text">0</h3>
                <small>每名学生平均选课数量</small>
            </div>
        </div>
    </div>
    <div class="col-md-6 mb-3">
        <div class="card bg-teal text-white">
            <div class="card-body text-center">
                <h5 class="card-title"><i class="fas fa-chart-pie"></i> 选课参与率</h5>
                <h3 id="participationRate" class="card-text">0%</h3>
                <small>参与选课的学生比例</small>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 性别分布图表 -->
    <div class="col-md-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="fas fa-venus-mars me-2"></i>性别分布</h5>
            </div>
            <div class="card-body">
                <canvas id="genderChart" height="250"></canvas>
            </div>
        </div>
    </div>

    <!-- 年级分布图表 -->
    <div class="col-md-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="fas fa-layer-group me-2"></i>年级分布</h5>
            </div>
            <div class="card-body">
                <canvas id="gradeChart" height="250"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 年龄分布图表 -->
    <div class="col-md-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="fas fa-birthday-cake me-2"></i>年龄分布</h5>
            </div>
            <div class="card-body">
                <canvas id="ageChart" height="100"></canvas>
            </div>
        </div>
    </div>

    <!-- 热门课程图表 -->
    <div class="col-md-6 mb-4">
        <div class="card" id="popularCoursesCard">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="fas fa-fire me-2"></i>热门课程排行</h5>
            </div>
            <div class="card-body">
                <canvas id="popularCoursesChart" height="100"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 选课分布图表 -->
    <div class="col-md-6 mb-4">
        <div class="card" id="courseDistributionCard">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="fas fa-chart-pie me-2"></i>选课分布</h5>
            </div>
            <div class="card-body">
                <canvas id="courseDistributionChart" height="250"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- 数据更新时间 -->
<div class="text-center text-muted mt-4">
    <small>数据最后更新时间: <span id="updateTime">-</span></small>
</div>
{% endblock %}
